<template>
  <div class="app-container">
    <el-card style="border-radius: 10px">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="工单编码" prop="workorderCode">
          <el-input
            v-model="queryParams.workorderCode"
            placeholder="请输入工单编码"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="工单名称" prop="workorderName">
          <el-input
            v-model="queryParams.workorderName"
            placeholder="请输入工单名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="计划编号" prop="planCode">
          <el-input
            v-model="queryParams.planCode"
            placeholder="请输入计划编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="计划名称" prop="planName">
          <el-input
            v-model="queryParams.planName"
            placeholder="请输入计划名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="产品编号" prop="productCode">
          <el-input
            v-model="queryParams.productCode"
            placeholder="请输入产品编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input
            v-model="queryParams.productName"
            placeholder="请输入产品名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="工单状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option
              v-for="dict in dict.type.mes_order_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <div style="height: 15px"></div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            :disabled="multiple"
            @click="handleAdd"
        >合并
        </el-button>
      </el-col>
    </el-row>
    <el-card style="border-radius: 10px">
      <el-table border v-loading="loading" :data="workorderList" ref="multipleTable" @select="handleSelect" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" :selectable="canSelectRow"/>
        <el-table-column label="工单编码" width="150" prop="workorderCode">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleView(scope.row)" v-hasPermi="['mes:pro:workorder:query']"
            >{{ scope.row.workorderCode }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          label="工单名称"
          width="150"
          align="center"
          prop="workorderName"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="工单进度" width="380" align="center" prop="workorderType">
          <template slot-scope="scope">
            <div v-if="scope.row.ganttDataList.length > 0" style="width: 100%">
              <div class="">
                <div
                  v-for="(item, index) in scope.row.ganttDataList"
                  :key="index"
                  style="width: 24%; margin-right: 1%"
                  class="res resesx reses flo_l"
                >
                  <el-tooltip
                    placement="bottom"
                    :content="
                      '工序:' +
                      item.process +
                      ' 产品名称:' +
                      item.product +
                      ' 完成比列:' +
                      (item.progress * 100 <= 100 ? item.progress * 100 : 100) +
                      '%'
                    "
                  >
                    <el-progress
                      :text-inside="true"
                      :stroke-width="16"
                      :percentage="item.progress * 100 <= 100 ? item.progress * 100 : 100"
                      :color="item.color"
                    ></el-progress>
                  </el-tooltip>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="图号" width="200" align="center" prop="attr2" :show-overflow-tooltip="true"/>
        <el-table-column label="关联计划" width="200" align="center" prop="planName" :show-overflow-tooltip="true"/>
        <el-table-column label="计划编号" width="150" align="center" prop="planCode" :show-overflow-tooltip="true"/>
        <el-table-column label="产品编号" width="120" align="center" prop="productCode" :show-overflow-tooltip="true"/>
        <el-table-column label="产品名称" width="100" align="center" prop="productName" :show-overflow-tooltip="true"/>
        <el-table-column label="规格型号" width="150" align="center" prop="productSpc" :show-overflow-tooltip="true"/>
        <el-table-column label="单位" width="60" align="center" prop="unitOfMeasure"/>
        <el-table-column label="需求日期" align="center" prop="requestDate" width="120">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.requestDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="计划开工时间" align="center" width="120px" prop="startDate">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="计划完工时间" align="center" width="120px" prop="endDate">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="实际开工时间" align="center" width="120px" prop="beginDate">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.beginDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="实际完工时间" align="center" width="120px" prop="finishDate">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.finishDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="工单数量" width="80" align="center" prop="quantity">
          <template slot-scope="scope">
            <el-tag type="danger">{{ scope.row.quantity }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="实际生产数量" width="120" align="center" prop="quantityProduced">
          <template slot-scope="scope">
            <el-tag type="success">{{ scope.row.quantityProduced }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="实际入库数量" width="120" align="center" prop="attr3">
          <template slot-scope="scope">
            <el-tag type="success">{{ scope.row.attr3 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="状态" align="left" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.mes_order_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="250px" align="left">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-refresh"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['mes:pro:workorder:biangeng']"
              v-if="scope.row.status == 'CONFIRMED'"
            >生产变更
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['mes:pro:workorder:paichan']"
              v-if="scope.row.status == 'PREPARE'"
            >生产排产
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-video-play"
              @click="getConfirmPage(scope.row)"
              v-hasPermi="['mes:pro:workorder:zhixing']"
              v-if="scope.row.status == 'PREPARE'"
            >执行工单
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-remove"
              @click="handleDied(scope.row)"
              v-hasPermi="['mes:pro:workorder:died']"
              v-if="scope.row.status !== 'DIED' && scope.row.status !== 'FINISHED'"
            >中止
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-refresh"
              @click="handleRestart(scope.row)"
              v-hasPermi="['mes:pro:workorder:died']"
              v-if="scope.row.status === 'DIED' "
            >开启
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改生产工单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="960px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px" disabled>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单编号">
              <el-input v-model="form.workorderCode" placeholder=""/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单名称">
              <el-input v-model="form.workorderName" placeholder=""/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划编号">
              <el-input v-model="form.planCode" placeholder=""/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划名称">
              <el-input v-model="form.planName" placeholder=""/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="来源类型" prop="orderSource">
              <el-radio-group v-model="form.orderSource" disabled>
                <el-radio v-for="dict in dict.type.mes_workorder_sourcetype" :key="dict.value" :label="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单编号" prop="sourceCode">
              <el-input v-model="form.sourceCode" placeholder=""/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据状态" prop="status">
              <el-select v-model="form.status" placeholder="">
                <el-option
                  v-for="dict in dict.type.mes_order_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品编号">
              <el-input v-model="form.productCode" placeholder=""/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品名称">
              <el-input v-model="form.productName" placeholder=""/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="规格型号">
              <el-input v-model="form.productSpc" placeholder=""/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位">
              <el-input v-model="form.unitOfMeasure" placeholder=""/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="BOM编号">
              <el-input v-model="form.bomCode" placeholder=""/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="BOM版本">
              <el-input v-model="form.bomName" placeholder=""/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划开工日期">
              <el-date-picker
                clearable
                readonly
                v-model="form.startDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择计划开工日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划完工日期">
              <el-date-picker
                clearable
                readonly
                v-model="form.endDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择计划完工日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单数量">
              <el-input-number :min="1" v-model="form.quantity" placeholder=""/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="需求日期" prop="requestDate">
              <el-date-picker
                clearable
                readonly
                v-model="form.requestDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择需求日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="图号" prop="attr2">
              <el-input v-model="form.attr2" placeholder=""/>
            </el-form-item>
          </el-col>
          <el-row>
            <el-col :span="12">
              <el-form-item label="客户名称" prop="clientName">
                <el-input v-model="form.clientName" placeholder=""/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="图纸集名称和版本" prop="drawCode">
              <el-input v-model="form.drawCode" placeholder=""/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="喷漆要求" prop="paintingRequirements">
              <el-input v-model="form.paintingRequirements" placeholder=""/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备方向" prop="deviceOrientation">
              <el-input v-model="form.deviceOrientation" placeholder=""/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="说明备注" prop="shuoming">
              <el-input v-model="form.shuoming" type="textarea" placeholder=""/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder=""/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-tabs type="border-card" v-if="form.workorderId != null">
        <el-tab-pane label="工艺流程">
          <div class="info-container">
            <div class="info-item">
              <span>工艺路线名称:</span>
              <span class="content">{{ form.routeName }}</span>
            </div>
            <div class="info-item">
              <span>工艺路线编号:</span>
              <span class="content">{{ form.routeCode }}</span>
            </div>
          </div>
          <div v-if="form.workorderId != null" :class="this.processOptions.length > 4 ? 'scroll-mode' : 'equal-mode'">
            <el-steps class="steps-container" :active="activeProcess" v-if="form.workorderId != null" align-center>
              <el-step
                v-for="(item, index) in processOptions"
                :key="item.processId"
                @click.native="handleStepClick(index)"
                :title="'工序' + (index + 1)"
                :description="item.processName"
              />
            </el-steps>
          </div>
          <el-card v-for="(item, index) in processOptions" :key="index" v-if="activeProcess == index">
            <template>
              <span>工序说明:</span>
              <span>{{ item.attr1 }}</span>
            </template>
            <ProTask
              :workorderId="form.workorderId"
              :routeId="item.routeId"
              :processId="item.processId"
              :colorCode="item.colorCode"
              :optType="optType"
              :quantity="form.quantity"
            ></ProTask>

          </el-card>
        </el-tab-pane>
        <el-tab-pane label="工序外协" v-if="outProcessOptions.length>0">
          <div class="info-container" style="    justify-content: flex-start">
            <div class="info-item">
              <span>来源类型:</span>
              <span class="content">{{ selectDictLabel(dict.type.mes_workorder_sourcetype, form.orderSource) }}</span>
            </div>
            <div class="info-item" v-if="form.orderSource == 'ORDER'">
              <span>销售订单:</span>
              <span class="content">{{ form.sourceCode }}</span>
            </div>
            <div class="info-item">
              <span>产品编号:</span>
              <span class="content">{{ form.productCode }}</span>
            </div>

            <div class="info-item">
              <span>产品名称:</span>
              <span class="content">{{ form.productName }}</span>
            </div>
          </div>
          <div class="info-container" style="    justify-content: flex-start">
            <div class="info-item" style="width:50%;display: flex;align-items: center;">
              <span style="width: 98px;font-size: 14px;
    color: #606266;
    font-weight: 800;">需求截至日期:</span>
              <el-date-picker
                clearable
                :disabled="optType == 'view' ||optType == 'confirm' || optType == 'finish'"
                v-model="form.outsourceDeadline"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择需求截至日期"
              >
              </el-date-picker>
            </div>
          </div>
          <el-table border v-loading="false" :data="outProcessOptions">
            <el-table-column label="工序编号" align="center" prop="processCode" :show-overflow-tooltip="true"/>
            <el-table-column label="工序名称" align="center" prop="processName" :show-overflow-tooltip="true"/>
            <el-table-column label="需求数量" align="center" :show-overflow-tooltip="true">
              <template>
                {{ form.quantity }}
              </template>
            </el-table-column>
          </el-table>
          <!--         <OutsourceWorkorder
                      :workorderCode="form.workorderCode"
                      :quantity="form.quantity"
                      :optType="optType"
                      :routeId="form.routeId"
                      :requestDate="form.requestDate"
                    ></OutsourceWorkorder>-->
        </el-tab-pane>
        <el-tab-pane label="物料清单">
          <el-table border v-loading="false" :data="workorderItemList">
            <el-table-column type="index" label="序号" width="55" align="center"/>
            <el-table-column label="物料编码" align="center" prop="itemCode" width="150" :show-overflow-tooltip="true"/>
            <el-table-column label="物料名称" align="center" prop="itemName" width="150" :show-overflow-tooltip="true"/>
            <el-table-column label="规格型号" align="center" prop="itemSpc" :show-overflow-tooltip="true"/>
            <el-table-column label="单位" width="100px" align="center" prop="unitOfMeasure" :show-overflow-tooltip="true"/>
            <el-table-column label="需求数量" width="120px" align="center" prop="quantity" :show-overflow-tooltip="true"/>
            <!--            <el-table-column label="用料比例" width="100px" align="center" prop="proportional"/>-->
            <el-table-column label="规格" align="center" prop="model" :show-overflow-tooltip="true"/>
            <el-table-column label="规格单位" align="center" width="80" prop="specificationUnit"/>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getItemList"
          />
        </el-tab-pane>
        <el-tab-pane label="领料记录">
          <el-table border v-loading="false" :data="issueheaderList">
            <el-table-column label="序号" type="index" width="50" align="center"/>
            <el-table-column label="领料单编号" align="center" width="150px" prop="issueCode"/>
            <el-table-column label="物料编号" align="center" prop="itemCode" width="120" :show-overflow-tooltip="true"/>
            <el-table-column label="物料名称" align="center" prop="itemName" width="150" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-tag type="primary">{{ scope.row.itemName }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="规格型号" align="center" prop="specification" width="80"/>
            <el-table-column label="单位" align="center" prop="unitOfMeasure" width="50"/>
            <el-table-column label="领料数量" align="center" prop="quantityIssued" width="80">
              <template slot-scope="scope">
                <el-tag type="success">{{ scope.row.quantityIssued }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="批次号" align="center" prop="batchCode" width="160" :show-overflow-tooltip="true"/>
            <el-table-column label="仓库名称" align="center" prop="warehouseName" width="120" :show-overflow-tooltip="true"/>
            <el-table-column label="库区名称" align="center" prop="locationName" width="120" :show-overflow-tooltip="true"/>
            <el-table-column label="库位名称" align="center" prop="areaName" width="150" :show-overflow-tooltip="true"/>
            <el-table-column label="领料时间" align="center" prop="createTime" width="100">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getIssueList"
          />
        </el-tab-pane>
        <el-tab-pane label="退料记录">
          <el-table border v-loading="false" :data="rtIssueList">
            <el-table-column label="序号" type="index" width="50" align="center"/>
            <el-table-column label="退料单编号" align="center" width="150px" prop="rtCode"/>
            <el-table-column label="物料编号" align="center" prop="itemCode" width="120" :show-overflow-tooltip="true"/>
            <el-table-column label="物料名称" align="center" prop="itemName" width="150" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-tag type="primary">{{ scope.row.itemName }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="规格型号" align="center" prop="specification" width="80"/>
            <el-table-column label="单位" align="center" prop="unitOfMeasure" width="50"/>
            <el-table-column label="退料数量" align="center" prop="quantityRt" width="80">
              <template slot-scope="scope">
                <el-tag type="success">{{ scope.row.quantityRt }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="批次号" align="center" prop="batchCode" width="160" :show-overflow-tooltip="true"/>
            <el-table-column label="仓库名称" align="center" prop="warehouseName" width="120" :show-overflow-tooltip="true"/>
            <el-table-column label="库区名称" align="center" prop="locationName" width="120" :show-overflow-tooltip="true"/>
            <el-table-column label="库位名称" align="center" prop="areaName" width="150" :show-overflow-tooltip="true"/>
            <el-table-column label="退料时间" align="center" prop="createTime" width="100">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getRtIssueList"
          />
        </el-tab-pane>
        <el-tab-pane label="补料记录" name="replenishment">
          <el-table border v-loading="false" :data="replenishmentList">
            <el-table-column label="序号" type="index" width="50" align="center"/>
            <el-table-column label="补料单编号" align="center" width="150px" prop="issueCode"/>
            <el-table-column label="物料编号" align="center" prop="itemCode" width="120" :show-overflow-tooltip="true"/>
            <el-table-column label="物料名称" align="center" prop="itemName" width="150" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-tag type="primary">{{ scope.row.itemName }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="规格型号" align="center" prop="specification" width="150" :show-overflow-tooltip="true"/>
            <el-table-column label="单位" align="center" prop="unitOfMeasure" width="50"/>
            <el-table-column label="补料数量" align="center" prop="quantityIssued" width="80">
              <template slot-scope="scope">
                <el-tag type="success">{{ scope.row.quantityIssued }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="批次号" align="center" prop="batchCode" width="160" :show-overflow-tooltip="true"/>
            <el-table-column label="仓库名称" align="center" prop="warehouseName" width="120" :show-overflow-tooltip="true"/>
            <el-table-column label="库区名称" align="center" prop="locationName" width="120" :show-overflow-tooltip="true"/>
            <el-table-column label="库位名称" align="center" prop="areaName" width="150" :show-overflow-tooltip="true"/>
            <el-table-column label="补料时间" align="center" prop="issueDate" width="100">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.issueDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="补料人名称" align="center" prop="issueUserName" width="150" :show-overflow-tooltip="true"/>
            <el-table-column label="补料原因" align="center" prop="issueReason" width="150" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <dict-tag
                  :options="dict.type.mes_issue_reason"
                  :value="scope.row.issueReason"
                />
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getRtIssueList"
          />
        </el-tab-pane>
        <el-tab-pane label="报工记录">
          <el-table
            border
            v-loading="false"
            :data="feedbackList"
          >
            <el-table-column label="报工类型" align="center" prop="feedbackType">
              <template slot-scope="scope">
                <dict-tag
                  :options="dict.type.mes_feedback_type"
                  :value="scope.row.feedbackType"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="工作站"
              width="150px"
              align="center"
              prop="workstationName"
            />
            <el-table-column
              label="生产工单编号"
              width="150px"
              align="center"
              prop="workorderCode"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="产品物料编码"
              width="120px"
              align="center"
              prop="itemCode"
            />
            <el-table-column
              label="产品物料名称"
              width="150px"
              align="center"
              prop="itemName"
              :show-overflow-tooltip="true"
            />
            <el-table-column label="规格型号" align="center" prop="specification"/>
            <el-table-column
              label="报工数量"
              align="center"
              prop="quantityFeedback"
            />
            <el-table-column label="报工人" align="center" prop="nickName"/>
            <el-table-column
              label="报工时间"
              align="center"
              prop="feedbackTime"
              width="100"
            >
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.feedbackTime, "{y}-{m}-{d}") }}</span>
              </template>
            </el-table-column>
            <el-table-column label="审核人" align="center" prop="recordNick"/>
            <el-table-column label="状态" align="center" prop="status">
              <template slot-scope="scope">
                <dict-tag
                  :options="dict.type.mes_order_status"
                  :value="scope.row.status"
                />
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getProFeedbackList"
          />
        </el-tab-pane>
        <el-tab-pane label="辅料领料记录">
          <el-table border v-loading="false" :data="accessorylineList">
            <el-table-column label="序号" type="index" width="50" align="center"/>
            <el-table-column label="辅料单编号" width="150px" align="center" prop="itemCode" :show-overflow-tooltip="true"/>
            <el-table-column label="物料编号" width="120px" align="center" prop="itemCode" :show-overflow-tooltip="true"/>
            <el-table-column label="物料名称" width="150px" align="center" prop="itemName" :show-overflow-tooltip="true"/>
            <el-table-column label="规格型号" width="80px" align="center" prop="specification" :show-overflow-tooltip="true"/>
            <el-table-column label="单位" width="50px" align="center" prop="unitOfMeasure" :show-overflow-tooltip="true"/>
            <el-table-column label="领料数量" width="80px" align="center" prop="quantityIssued">
              <template slot-scope="scope">
                <el-tag type="success">{{ scope.row.quantityIssued }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="批次号" width="160" align="center" prop="batchCode" :show-overflow-tooltip="true"/>
            <el-table-column label="仓库名称" width="120" align="center" prop="warehouseName" :show-overflow-tooltip="true"/>
            <el-table-column label="库区名称" width="120" align="center" prop="locationName" :show-overflow-tooltip="true"/>
            <el-table-column label="库位名称" width="150" align="center" prop="areaName" :show-overflow-tooltip="true"/>
            <el-table-column label="领料时间" align="center" prop="createTime" width="100">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel" v-if="optType == 'view'">返 回</el-button>
        <el-button type="primary" @click="submitForm" v-if="optType != 'view' && optType != 'confirm' && optType != 'finish'">保 存</el-button>
        <el-button type="danger" @click="handDofinish" v-if="optType == 'finish'">完 工</el-button>
        <el-button type="danger" @click="handleConfirm" v-if="optType == 'confirm'">执行工单</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <SchedulingLine v-if="open2" @cancelMerger="cancelMerger" @refreshList="getList" ref="schedulingLine" :ids="this.ids"></SchedulingLine>
  </div>
</template>

<script>
import { addWorkorder, died, dofinish, getWorkorder, listWorkorder, restart, updateWorkorder } from '@/api/mes/pro/workticket';
import ProTask from './task/proTask.vue';
import { listProcess } from '@/api/mes/pro/routeprocess';
import { getBomGl } from '@/api/mes/md/bomgl';
import { listGanttTaskList } from "@/api/mes/pro/protask";
import { getRtListIssueline } from "@/api/mes/wm/rtissueline";
import { listFeedback } from "@/api/mes/pro/feedback";
import { getlistIssueline } from '@/api/mes/wm/issueline';
import { listWorkorderbom } from '@/api/mes/pro/workorderbom';
import { getReplenishmentList } from "@/api/mes/wm/replenishment";
import { listAccessory } from "@/api/mes/wm/accessoryline";
import Template from "@/views/print/printtemplate/list.vue";
import OutsourceWorkorder from './outsource/workorder.vue'
import { selectDictLabel } from "../../../../utils/ruoyi";
import { addTaskScheduling } from "@/api/monitor/job";
import SchedulingLine from "@/views/mes/pro/workticket/line.vue";

export default {
  name: 'Workorder',
  dicts: ['mes_order_status', 'mes_workorder_sourcetype', 'mes_workorder_type', 'mes_feedback_type', 'mes_issue_reason'],
  components: {
    Template,
    ProTask,
    OutsourceWorkorder,
    SchedulingLine
  },
  data() {
    return {
      outsourceWorkorderList: [],
      outProcessOptions: [],
      //新建外协工单时，外协工序中剩余的外协工序
      processLeft: [],
      activeProcess: 0,
      optType: undefined,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      selectedAttr1: [],
      // 非单个禁用
      single: true,
      // 总条数
      total: 0,
      // 非多个禁用
      multiple: true,
      // 生产工单表格数据
      workorderList: [],
      // 生产工单树选项
      workorderOptions: [],
      processOptions: [],
      workorderItemList: [],
      rtIssueList: [],
      feedbackList: [],
      issueheaderList: [],
      replenishmentList: [],
      accessorylineList: [],
      bom: {},
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      open2: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        workorderCode: null,
        workorderName: null,
        orderSource: null,
        sourceCode: null,
        productId: null,
        productCode: null,
        productName: null,
        productSpc: null,
        unitOfMeasure: null,
        quantity: null,
        quantityProduced: null,
        quantityChanged: null,
        quantityScheduled: null,
        clientId: null,
        clientCode: null,
        clientName: null,
        requestDate: null,
        parentId: null,
        ancestors: null,
        status: null
      },
      // 表单参数
      form: {},
      queryParam: {
        pageNum: 1,
        pageSize: 10,
        workorderId: null,
        status: null,
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    selectDictLabel,
    /** 查询生产工单列表 */
    getList() {
      this.loading = true;
      listWorkorder(this.queryParams).then(response => {
        this.workorderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.open2 = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        workorderId: null,
        workorderCode: null,
        workorderName: null,
        workorderType: 'SELF',
        orderSource: null,
        sourceCode: null,
        productId: null,
        productCode: null,
        productName: null,
        productSpc: null,
        unitOfMeasure: null,
        quantity: null,
        quantityProduced: null,
        quantityChanged: null,
        quantityScheduled: null,
        clientId: null,
        clientCode: null,
        clientName: null,
        vendorId: null,
        vendorCode: null,
        vendorName: null,
        requestDate: null,
        parentId: null,
        status: 'PREPARE',
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        batchCode: null
      };
      this.activeProcess = 0;
      this.autoGenCodeFlag = false;
      this.selectedAttr1 = [];
      this.ids = [];
      this.single = true;
      this.multiple = true;
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },

    // 查询明细按钮操作
    handleView(row) {
      this.reset();
      const workorderId = row.workorderId || this.ids;
      getWorkorder(workorderId).then(response => {
        this.form = response.data;
        this.getProcess();
        this.getProFeedbackList();
        this.getRtIssueList();
        this.getIssueList();
        this.getItemList();
        this.getReplenishmentList();
        this.getAccessoryList();
        this.open = true;
        this.title = '查看工单信息';
        this.optType = 'view';
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      if (row != null) {
        this.form.parentId = row.workorderId;
      }
      getWorkorder(row.workorderId).then(response => {
        this.form = response.data;
        this.getProcess();
        this.getProFeedbackList();
        this.getRtIssueList();
        this.getIssueList();
        this.getItemList();
        this.open = true;
        this.title = '生产排产';
        this.optType = 'edit';
      });
    },

    // 完成按钮操作
    handleFinish(row) {
      if (row.quantityProduced !== row.attr3) {
        this.$modal.msgError('实际生产数量与入库数量不符，请先完成产品入库');
        return;
      }
      this.reset();
      const workorderId = row.workorderId || this.ids;
      getWorkorder(workorderId).then(response => {
        this.form = response.data;
        this.getProcess();
        this.getProFeedbackList();
        this.getRtIssueList();
        this.getIssueList();
        this.getItemList();
        this.open = true;
        this.title = '完成工单信息';
        this.optType = 'finish';
      });
    },
    handleFinish2(row) {
      this.reset();
      this.form.workorderId = row.workorderId || this.ids;
      this.open2 = true;
      this.title = '完成工单';
      this.optType = 'finish';
    },
    getConfirmPage(row) {
      this.reset();
      const workorderId = row.workorderId || this.ids;
      getWorkorder(workorderId).then(response => {
        this.form = response.data;
        this.getProcess();
        this.getProFeedbackList();
        this.getRtIssueList();
        this.getIssueList();
        this.getItemList();
        this.open = true;
        this.title = '确认工单信息';
        this.optType = 'confirm';
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.workorderId != null) {
            updateWorkorder(this.form).then(response => {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              //this.$refs['bomlist'].getList();
              this.getList();
            });
          } else {
            addWorkorder(this.form).then(response => {
              this.$modal.msgSuccess('新增成功');
              //this.open = false;
              this.form.workorderId = response.data;
              this.getList();
            });
          }
        }
      });
    },
    handleConfirm() {
      let that = this;
      that.$modal.confirm('是确认完成生产任务编制？【确认后将不能更改】').then(function () {
        that.form.status = 'CONFIRMED';
        that.form.quantity = null;
        updateWorkorder(that.form)
          .then(() => {
            addTaskScheduling(that.form.workorderId)
          })
          .then(() => {
            that.$modal.msgSuccess('修改成功');
            that.getList();
            that.open = false;
          })
          .catch(error => {
            console.error("updateWorkorder 执行失败：", error);
            //that.$modal.msgError('修改失败，请稍后重试');
          });
      })
        .catch(() => {
        });
    },
    handDofinish() {
      const workorderIds = this.form.workorderId || this.ids;
      let msg = "是否确认完成工单？一旦完成，此工单将无法继续报工和入库";
      if (this.form.quantity != this.form.quantityProduced) {
        msg = '工单数量与实际生产数量不一致，是否确认完成工单，一旦完成，此工单将无法继续报工和入库？';
      }
      this.$modal.confirm(msg).then(() => {
        return dofinish(workorderIds);
      })
        .then(() => {
          this.getList();
          this.open = false;
          this.$modal.msgSuccess('更改成功');
        })
        .catch(() => {
        });

    },
    getBom() {
      getBomGl(this.form.bomId).then(response => {
        this.bom = response.data;
      });
    },
    //获取当前产品对应的生产工序
    getProcess() {
      listProcess(this.form.routeId, 'N').then(response => {
        this.processOptions = response.data;
      });
      listProcess(this.form.routeId, 'Y').then(response => {
        this.outProcessOptions = response.data;
      });
    },
    //Step点击
    handleStepClick(index) {
      this.activeProcess = index;
    },
    //物料清单
    getItemList() {
      this.workorderItemList = [];
      this.queryParam.status = null;
      this.queryParam.workorderId = this.form.workorderId;
      listWorkorderbom(this.queryParam).then(response => {
        if (response.code == 200 && response.rows) {
          this.workorderItemList = response.rows;
          this.total = response.total;
        }
      })
    },
    //领料记录
    getIssueList() {
      this.queryParam.status = 'FINISHED';
      this.queryParam.workorderId = this.form.workorderId;
      getlistIssueline(this.queryParam).then(response => {
        if (response.code == 200) {
          this.issueheaderList = response.rows;
          this.total = response.total;
        }
      })
    },
    //退料记录
    getRtIssueList() {
      this.queryParam.status = 'FINISHED';
      this.queryParam.workorderId = this.form.workorderId;
      getRtListIssueline(this.queryParam).then(response => {
        if (response.code == 200) {
          this.rtIssueList = response.rows;
          this.total = response.total;
        }
      })
    },
    //报工记录
    getProFeedbackList() {
      this.queryParam.status = 'FINISHED';
      this.queryParam.workorderId = this.form.workorderId;
      listFeedback(this.queryParam).then(response => {
        if (response.code == 200 && response.rows) {
          this.feedbackList = [];
          this.feedbackList = response.rows;
          this.total = response.total;
        }
      })
    },
    //补料记录
    getReplenishmentList() {
      this.queryParam.status = 'FINISHED';
      this.queryParam.workorderId = this.form.workorderId;
      getReplenishmentList(this.queryParam).then(response => {
        if (response.code == 200) {
          this.replenishmentList = response.rows;
          this.total = response.total;
        }
      })
    },
    //辅料领料记录
    getAccessoryList() {
      this.queryParam.status = 'FINISHED';
      this.queryParam.workorderId = this.form.workorderId;
      listAccessory(this.queryParam).then(response => {
        if (response.code == 200) {
          this.accessorylineList = response.rows;
          this.total = response.total;
        }
      });
    },
    // 中止
    handleDied(row) {
      this.$modal
        .confirm('是否确认中止工单？')
        .then(function () {
          return died({workorderId: row.workorderId});
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("操作成功");
        })
        .catch(() => {
        });
    },
    // 中止
    handleRestart(row) {
      this.$modal
        .confirm('是否确认开启工单？')
        .then(function () {
          return restart({workorderId: row.workorderId});
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("操作成功");
        })
        .catch(() => {
        });
    },
    /** 新增按钮操作 */
    handleAdd() {
      if (!this.ids || this.ids.length < 2) {
        this.$message.warning('请至少选择两个工单进行合并操作！');
        return;
      }
      this.open2 = true;
      this.title = '合并工单';
      this.$nextTick(() => {
        this.$refs.schedulingLine.init(this.ids);
      });
    },
    // 当用户点击勾选框时触发
    handleSelect(selection, row) {
      if (selection.length === 1) {
        // 选中的第一条，记录 attr1 的值
        this.selectedAttr1 = row.attr1;
      } else {
        // 检查是否 attr1 不一致
        if (row.attr1 !== this.selectedAttr1) {
          this.$refs.multipleTable.toggleRowSelection(row, false); // 取消本次选择
          this.$message.warning('请选择物料及制程相同的工单进行合并！');
        }
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      // 如果没有选中项，清空状态
      if (selection.length === 0) {
        this.selectedAttr1 = null;
        this.ids = [];
        this.single = true;
        this.multiple = true;
        return;
      }

      // 基准 attr1，基于第一条选中记录
      const baseAttr1 = selection[0].attr1;
      this.selectedAttr1 = baseAttr1;

      // 保留 attr1 相同的记录
      const validSelection = [];

      for (const row of selection) {
        if (row.attr1 === baseAttr1) {
          validSelection.push(row);
        } else {
          this.$refs.multipleTable.toggleRowSelection(row, false); // 取消不一致的项
        }
      }

      // 弹出警告
      if (validSelection.length !== selection.length) {
        this.$message.warning("请选择物料及制程相同的工单进行合并！");
      }

      // 只设置有效选项
      this.ids = validSelection.map(item => item.workorderId);
      this.single = validSelection.length !== 1;
      this.multiple = validSelection.length === 0;
    },
    canSelectRow(row, index) {
      return row.status === 'PREPARE' && row.orderSource != 'MERGER';
    },
    // 取消按钮
    cancelMerger() {
      this.$refs.multipleTable.clearSelection();
      this.reset();
      this.open2 = false;
    },
  }
};
</script>
<style scoped>

/* 1. 滚动模式：固定宽度，允许横向滚动 */
.scroll-mode {
  overflow-x: auto;
  white-space: nowrap;
}

.scroll-mode .steps-container {
  display: inline-flex;
  min-width: max-content;
}

.scroll-mode /deep/ .el-step {
  flex: 0 0 180px !important;
}

/* 2. 平均分配模式：步数少，平均撑满整行 */
.equal-mode .steps-container {
  display: flex;
  width: 100%;
}

.equal-mode ::v-deep(.el-step) {
  flex: 1 1 0; /* 自动平均分配 */
}

.wrapper {
  height: 400px;
}

.container {
  height: 100%;
  width: 100%;
}

.left-container {
  overflow: hidden;
  position: relative;
  height: 100%;
}

.info-container {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.info-item {
  width: 30%; /* Adjust width as needed */
  margin-bottom: 20px;
}

.info-item span {
  margin-left: 10px;
}

.info-item span:first-child {
  font-family: '苹方 常规', '苹方', sans-serif;
  font-weight: 400;
  font-style: normal;
  font-size: 14px;
  color: #262626;
  text-align: left;
  line-height: 20px;
  display: inline-block;
}

.content {
  color: #8c8c8c;
  text-align: left;
}
</style>

<style lang="scss" scoped>
@import url('../../../../assets/common/css/common.css');
</style>
